package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorsMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorsMapper dishFlavorsMapper;
    @Autowired
    private SetMealDishMapper setMealDishMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品和对于的口味
     * @param dishDTO
     */
    @Override
    @Transactional //事务！
    public void addDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //给菜品表插入1条数据
        dishMapper.insert(dish);

        Long id = dish.getId();
        //给口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null&& !flavors.isEmpty()){
            for(DishFlavor df:flavors){
                df.setDishId(id);
            }

            dishFlavorsMapper.addFlavors(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除
     * @param dishIds
     */
    @Override
    @Transactional
    public void deleteDish(List<Long> dishIds) {
        for (Long dishId : dishIds) {
            Dish dish = dishMapper.getById(dishId);
            //要求1，起售的不能删
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException("这个东西还在卖了，不能删啊");
            }

        }
        //要求2，被套餐关联住的不能删
        List<Long> ls = setMealDishMapper.getByDishId(dishIds);
        if (ls!=null && !ls.isEmpty()) {
            throw new DeletionNotAllowedException("菜品被关联了呀，删不了");
        }


//        for (Long Id : dishIds) {
//            //操作1，删除菜品表单中的数据
//            dishMapper.deleteById(Id);
//            //操作2，删除菜品关联的口味表
//            dishFlavorsMapper.deleteByDishId(Id);
//        }
        //优化删除sql
        dishMapper.deleteByIds(dishIds);
        dishFlavorsMapper.deleteByDishIds(dishIds);


    }

    /**
     * 查询菜品信息，包含基础+口味，用于修改前的回写
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        Dish dish = dishMapper.getById(id);
        List<DishFlavor> dishFlavors = dishFlavorsMapper.getByDishId(id);

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 更新菜品的信息，包含基础+口味
     * @param dishVO
     */
    @Override
    @Transactional //事务！
    public void updateWithFlavor(DishVO dishVO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishVO,dish);
        //基础信息修改
        dishMapper.update(dish);
        //口味数据修改比较巧妙，方法是 -> 先删除 再插入 因为口味数据的变动情况很多，不方便统一
        Long dishId = dishVO.getId();
        dishFlavorsMapper.deleteByDishId(dishId);
        List<DishFlavor> dishFlavors = dishVO.getFlavors();
        if(dishFlavors!=null&& !dishFlavors.isEmpty()){
            for(DishFlavor df:dishFlavors){
                df.setDishId(dishId);
            }
            dishFlavorsMapper.addFlavors(dishFlavors);
        }

    }

    /**
     * 根据菜品分类信息查所有的菜品
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        //我加入了缓存！

        //构建key
        String KEY = "listCache:"+"category_Id=" + dish.getCategoryId();
        //查询一下
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(KEY);
        if (list!=null&& !list.isEmpty()) {
            //返回前端redis中的数据就可以了
            return list;
        }
        //没有存在

        List<Dish> list1 = dishMapper.getByCategoryId(dish.getCategoryId());
        List<DishVO> dishVOList = new ArrayList<>();

        //补充这个菜的信息
        for(Dish d:list1){
            //封装为VO
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            //根据这个菜的id查这个菜的口味
            List<DishFlavor> flavors = dishFlavorsMapper.getByDishId(d.getId());

            //补充VO信息
            dishVO.setFlavors(flavors);
            //放入列表
            dishVOList.add(dishVO);

        }
        redisTemplate.opsForValue().set(KEY,dishVOList);
        return dishVOList;
    }

    @Override
    public void changeDishStatus(Integer status, Integer id) {
        if (status == 0) {
            dishMapper.disenableDish(id);
        }
        else if (status == 1) {
            dishMapper.enableDish(id);
        }
    }


/*    @Override
    public List<DishVO> getDishesByCategoryId(Integer categoryId) {
        return (dishMapper.getByCategoryId(categoryId));
    }*/
}
